import { CanActivate, ExecutionContext, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { UserService } from './user.service';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { RedisService } from '../redis/redis.service';

@Injectable()
export class PermissionGuard implements CanActivate {
  
  @Inject(UserService)
  private userService: UserService;

  //可以获取元数据
  @Inject('Reflector')
  private reflector : Reflector;

  @Inject(RedisService)
  private redisService : RedisService;


  async canActivate(
    context: ExecutionContext, 
  ):Promise<boolean> {
    const request : Request = context.switchToHttp().getRequest();
    const user = request.session.user;
    if(!user){ throw new UnauthorizedException('用户未登录'); }

    //先查redis
    let permissions = await this.redisService.listGet(`user_${user.username}_permission`);
    if(permissions.length === 0){
      const finduser = await this.userService.findByUsername(user.username);
      permissions = finduser.permissions.map(item=>item.name);
     
      console.log(finduser,permissions);
      await this.redisService.listSet(`user_${user.username}_permission`,permissions,60*30);
    }else{
      console.log(permissions);
    }


    //从当前请求的处理程序（Handler）中获取名为 permission 的元数据。
    //它返回一个对象，该对象包含了当前请求所对应的控制器方法、中间件等信息。
    const permission = this.reflector.get('permission',context.getHandler())

    if(permissions.includes(permission)){
      return true;
    }else{
      throw new UnauthorizedException('没有权限访问该接口');
    }

  }
}
